package org.ceteca.explica.client.partners;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import org.ceteca.explica.client.ClientContext;
import org.ceteca.explica.client.gui.ExplicaGUIBuilder;
import org.ceteca.explica.client.gui.common.CommonClient;
import org.ceteca.explica.core.ExplicaException;
import org.ceteca.explica.core.InterfaceErrors;
import org.ceteca.explica.core.common.BaseVO;
import org.ceteca.explica.core.common.CommonManager;
import org.ceteca.explica.core.common.CountryOT;
import org.ceteca.explica.core.common.StateOT;
import org.ceteca.explica.core.partners.AddressOT;
import org.ceteca.explica.core.partners.ContactOT;
import org.ceteca.explica.core.partners.InterfacePartners;
import org.ceteca.explica.core.partners.InterfacePartnersErrors;
import org.ceteca.explica.core.partners.PartnerOT;
import org.ceteca.explica.core.util.Converter;
import org.ceteca.explica.core.util.OperationResult;
import org.ceteca.javaglade.InterfaceGladeGtk;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Text;
/**
 * @author Juan C. Díaz (juancarlosdiaz@ceteca.net) <br>
 *         Copyright (c) 2009 Fundación Centro Tecnolóxico da Carne
 * 
 * <br>
 * <br>
 *         This program is free software: you can redistribute it and/or modify
 *         it under the terms of the GNU General Public License as published by
 *         the Free Software Foundation, either version 3 of the License, or (at
 *         your option) any later version. <br/>
 *         This program is distributed in the hope that it will be useful, but
 *         WITHOUT ANY WARRANTY 
 *         <br>without even the implied warranty of
 *         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *         General Public License for more details. <br/>
 *         You should have received a copy of the GNU General Public License
 *         along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
public class AddressClient extends CommonClient {

	private Text entryAddressId, entryAddressDescription, entryAddressAddress,
			entryAddressPoBox, entryAddressPostalCode, entryAddressCity;
	private Text entryVersion;

	private Button buttonAddressShippingAddress, buttonAddressBillingAddress,
			buttonAddressViewMap;
	private Combo comboAddressCountry, comboAddressState;

	private ArrayList<CountryOT> countries = new ArrayList<CountryOT>();
	private ArrayList<StateOT> states = new ArrayList<StateOT>();

	private AddressListener addressListener;
	




	public AddressClient() {
		super(	AddressOT.class, 
				InterfacePartners.EXPLICA_EDIT_ADDRESS_GLADE_PATH,

				InterfacePartners.EDIT_ADDRESS_DIALOG_NAME);
		

	}








	@Override
	public void build_extension_fields_view() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void buildSelectionSets() {
		// TODO Auto-generated method stub
		
	}



	public Combo getComboAddressCountry() {
		return comboAddressCountry;
	}

	public Combo getComboAddressState() {
		return comboAddressState;
	}

	public ArrayList<CountryOT> getCountries() {
		return countries;
	}

	@Override
	public BaseVO getEntityData() {

		AddressOT entity = new AddressOT();
		if (this.entEditView != null) {
			this.getWidgets();
			entity.setDescription(entryAddressDescription.getText());
			entity.setAddress(entryAddressAddress.getText());
			entity.setCity(entryAddressCity.getText());
			entity.setPoBox(entryAddressPoBox.getText());
			entity.setPostalCode(entryAddressPostalCode.getText());
			entity
					.setBillingAddress(buttonAddressBillingAddress
							.getSelection());
			entity.setShippingAddress(buttonAddressShippingAddress
					.getSelection());

			int selectedCountry = comboAddressCountry.getSelectionIndex();
			if (selectedCountry > -1)
				entity.setCountry(countries.get(selectedCountry));

			int selectedState = comboAddressState.getSelectionIndex();
			if (selectedState > -1)
				entity.setState(states.get(selectedState));

			if (selectedEntity != null) {
				entity.setVersion(((AddressOT) this.selectedEntity)
						.getVersion());
				entity.setIdAddress(((AddressOT) this.selectedEntity)
						.getIdAddress());
			}
		}

		return entity;
	}

	public ArrayList<StateOT> getStates() {
		return states;
	}



	public void getWidgets() {

		boolean allOk = true;

		if ((entryAddressId = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_ID_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_ID_WIDGETNAME);

		}

		if ((entryAddressDescription = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_DESCRIPTION_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_DESCRIPTION_WIDGETNAME);

		}
		if ((entryAddressAddress = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_ADDRESS_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_ADDRESS_WIDGETNAME);

		}

		if ((entryAddressCity = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_CITY_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_CITY_WIDGETNAME);

		}
		if ((entryAddressPoBox = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_POBOX_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_POBOX_WIDGETNAME);

		}
		if ((comboAddressState = ((Combo) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_STATE_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_STATE_WIDGETNAME);

		}

		if ((buttonAddressBillingAddress = ((Button) this
				.getWidget(
						InterfacePartners.EDIT_ADDRESS_BILLINGADDRESS_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_BILLINGADDRESS_WIDGETNAME);

		}

		if ((buttonAddressShippingAddress = ((Button) this
				.getWidget(
						InterfacePartners.EDIT_ADDRESS_SHIPPINGADDRESS_WIDGETNAME))) == null) {
			allOk = false;
			this.logger
					.error("Error getting entry Address Widget:"
							+ InterfacePartners.EDIT_ADDRESS_SHIPPINGADDRESS_WIDGETNAME);

		}

		if ((comboAddressCountry = ((Combo) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_COUNTRY_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_COUNTRY_WIDGETNAME);

		}
		if ((entryAddressPostalCode = ((Text) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_ZIPCODE_WIDGETNAME))) == null) {
			allOk = false;
			this.logger.error("Error getting entry Address Widget:"
					+ InterfacePartners.EDIT_ADDRESS_ZIPCODE_WIDGETNAME);

		}

		if ((buttonAddressViewMap = ((Button) this.getWidget(
				InterfacePartners.EDIT_ADDRESS_VIEW_MAP_BUTTON_WIDGETNAME))) == null) {
			allOk = false;
			this.logger
					.error("Error getting entry Address Widget:"
							+ InterfacePartners.EDIT_ADDRESS_VIEW_MAP_BUTTON_WIDGETNAME);

		}

		if ((entryVersion = ((Text) this.getWidget(
				InterfacePartners.EDIT_VERSION_WIDGETNAME))) == null) {
			allOk = false;


		}
		
		
		if (!allOk)
			System.exit(-1);

	}

	@Override
	public void init_specific_components() {
		this.addressListener=new AddressListener(this);
		
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, comboAddressCountry,
				"on_country_combo_changed", addressListener);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CLICKED,
				buttonAddressViewMap, "on_button_map_view_clicked", addressListener);
		

	}








	public void loadCountries() {
		countries.clear();

		OperationResult result = new OperationResult();
		List<BaseVO> list = null;
		CommonManager manager;
		try {
			manager = this.getRemote();
			list = manager.queryEntities(null, "", CountryOT.class);
			if (list != null)
				this.logger.info("Retrieved " + list.size() + " countries");
			else
				this.logger.error("No countries found");
			result.addResultMessage(OperationResult.RESULT_OK, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfacePartnersErrors.MSG_ENTITY_RETRIVE_OK));
		} catch (ExplicaException e) {
			result
					.addResultMessage(OperationResult.RESULT_ERROR, e
							.getResMsg());
			e.printStackTrace();
		} catch (RemoteException e) {
			result
					.addResultMessage(
							OperationResult.RESULT_ERROR,
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.newResultMessage(
											InterfacePartnersErrors.ERR_RMI_METHOD_NOT_FOUND,
											e));
			e.printStackTrace();
		}
		if (result.getResult() != OperationResult.RESULT_OK) {
			ExplicaGUIBuilder.getInstance().showConfirmationDialog(
					this.entEditView.getGui().getParentWindow().getShell(),
					result.getFormattedResult(), "", SWT.ICON_ERROR, SWT.OK);
		} else if (list != null)
			for (BaseVO item : list)
				countries.add((CountryOT) item);

	}








	public void loadStates(CountryOT country) {
		states.clear();
		if (country == null)
			return;
		OperationResult result = new OperationResult();
		List<BaseVO> list = null;
		CommonManager manager;
		try {
			manager = this.getRemote();
			list = manager.queryEntities("country", country, StateOT.class);

			// list = manager.queryStatesByCountry(country.getIdCountry());

			result.addResultMessage(OperationResult.RESULT_OK, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.MSG_ENTITY_RETRIVE_OK));
		} catch (ExplicaException e) {
			result
					.addResultMessage(OperationResult.RESULT_ERROR, e
							.getResMsg());
			e.printStackTrace();
		} catch (RemoteException e) {
			result.addResultMessage(OperationResult.RESULT_ERROR, ClientContext
					.getInstance().getMsgCatalog().newResultMessage(
							InterfaceErrors.ERR_RMI_METHOD_NOT_FOUND, e));
			e.printStackTrace();
		}
		if (result.getResult() != OperationResult.RESULT_OK) {
			ExplicaGUIBuilder.getInstance().showConfirmationDialog(
					this.entEditView.getGui().getParentWindow().getShell(),
					result.getFormattedResult(), "", SWT.ICON_ERROR, SWT.OK);
		} else if (list != null)
			for (BaseVO item : list)
				states.add((StateOT) item);

	}








	@Override
	public OperationResult printEntity(){
		OperationResult result=new OperationResult();
		String reportPath=InterfacePartners.EXPLICA_PARTNERS_ADDRESS_REPORT;
		result.add(printEntity(reportPath, null));
		return result;
	}








	public void setComboAddressCountry(Combo comboAddressCountry) {
		this.comboAddressCountry = comboAddressCountry;
	}








	public void setComboAddressState(Combo comboAddressState) {
		this.comboAddressState = comboAddressState;
	}








	public void setCountries(ArrayList<CountryOT> countries) {
		this.countries = countries;
	}








	@Override
	public void setEditionMode(boolean enabled) {
		getWidgets();
		entryAddressId.setEnabled(false);
		entryVersion.setEnabled(false);
		entryAddressAddress.setEnabled(enabled);
		entryAddressCity.setEnabled(enabled);
		entryAddressDescription.setEnabled(enabled);
		entryAddressPoBox.setEnabled(enabled);
		entryAddressPostalCode.setEnabled(enabled);
		buttonAddressBillingAddress.setEnabled(enabled);
		buttonAddressShippingAddress.setEnabled(enabled);
		buttonAddressViewMap.setEnabled(enabled);
		comboAddressCountry.setEnabled(enabled);
		comboAddressState.setEnabled(enabled);
	}








	public void setStates(ArrayList<StateOT> states) {
		this.states = states;
	}








	public void setWidgetsValues(BaseVO entity) {

		
		AddressOT ent=(AddressOT)entity;
		getWidgets();
		entryAddressId.setText(Converter.getInstance().toString(
				ent.getIdAddress()));
		entryAddressDescription.setText(ent.getDescription() == null ? "" : ent
				.getDescription());
		entryAddressCity.setText(ent.getCity() == null ? "" : ent.getCity());
		entryAddressAddress.setText(ent.getAddress()==null?"":ent.getAddress());
		entryAddressPoBox.setText(ent.getPoBox()==null?"":ent.getPoBox());
		entryAddressPostalCode.setText(ent.getPostalCode()==null?"":ent.getPostalCode());
		entryVersion.setText(Converter.getInstance().toString(ent.getVersion()));
		buttonAddressBillingAddress.setSelection(ent.isBillingAddress());
		buttonAddressShippingAddress.setSelection(ent.isShippingAddress());

		loadCountries();

		comboAddressCountry.removeAll();
		int selected = -1;
		for (int i = 0; i < countries.size(); i++) {
			CountryOT f = countries.get(i);
			comboAddressCountry.add(f.getName());
			if (ent.getCountry() != null)
				if (f.getIdCountry() == ent.getCountry().getIdCountry()) {
					selected = i;
					// break;
				}
		}
		
		
		if (selected > -1 && ent.getCountry() != null)
			comboAddressCountry.select(selected);

		loadStates(ent.getCountry());

		comboAddressState.removeAll();
		selected = -1;
		for (int i = 0; i < states.size(); i++) {
			StateOT f = states.get(i);
			comboAddressState.add(f.getName());
			if (ent.getState() != null)
				if (f.getIdState() == ent.getState().getIdState()) {
					selected = i;
					// break;
				}
		}
		if (selected > -1 && ent.getState() != null)
			comboAddressState.select(selected);

	}


	@Override
	public OperationResult validateEntity() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void fillEntityData() {
		if (this.selectedEntity != null && this.entEditView != null) {
			getWidgets();
			setWidgetsValues((AddressOT) selectedEntity);
		}
	}
}